package com.situ.skymallcartapi.api;

import com.situ.model.Cart;
import com.situ.service.CartService;
import com.situ.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping(value = "/api/v1/carts",produces = MediaType.APPLICATION_JSON_VALUE)
public class CartApi {
    private CartService cartService;


    @Autowired
    public void setCartService(CartService cartService) {
        this.cartService = cartService;
    }

    //根据会员编号查询指定会员的所有购物车项
    @GetMapping
    public ResponseEntity<JsonResult<?>> findAll(Integer userId) {

        List<Cart> list = cartService.findByUserId(userId);

        return ResponseEntity.ok(JsonResult.success(list));
    }

    @GetMapping("/id/{id}")
    public ResponseEntity<JsonResult<?>>findById(@PathVariable Integer id){
       Cart cart=cartService.findById(id);
       if (cart==null){
           return ResponseEntity.ok(JsonResult.fail("购物车不存在"));
       }else {
           return ResponseEntity.ok(JsonResult.success(cart));
       }
    }
    @PostMapping
    public ResponseEntity<JsonResult<?>> save(@RequestBody Cart cart) {
        boolean success = cartService.save(cart);
        if (success) {
            return ResponseEntity.ok(JsonResult.success());
        } else {
            return ResponseEntity.ok(JsonResult.fail("保存购物车项失败"));
        }
    }

    @PutMapping
    public ResponseEntity<JsonResult<?>> update(@RequestBody Cart cart) {
        boolean success = cartService.update(cart);
        if (success) {
            return ResponseEntity.ok(JsonResult.success());
        } else {
            return ResponseEntity.ok(JsonResult.fail("修改购物车项失败"));
        }
    }

    @DeleteMapping
    public ResponseEntity<JsonResult<?>> deleteByIds(@RequestBody Integer[] ids) {
        Objects.requireNonNull(ids);
        int count = cartService.deleteByIds(List.of(ids));
        if (count > 0) {
            return ResponseEntity.ok(JsonResult.success(count));
        } else {
            return ResponseEntity.ok(JsonResult.fail("购物车项删除失败"));
        }
    }
}
